package com.zj.osm.utils.db_utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Point;
import android.os.Environment;
import android.util.Log;

import com.google.android.gms.maps.model.LatLng;
import com.zj.osm.App;
import com.zj.osm.bean.SendPointResult;
import com.zj.osm.entity.db.LineDao;
import com.zj.osm.entity.db.PointDao;
import com.zj.osm.entity.greendao.Line;
import com.zj.osm.entity.greendao.Project;
import com.zj.osm.model.pojo.Module;
import com.zj.osm.utils.AngleUtil;
import com.zj.osm.utils.SQLiteDatabaseUtils;
import com.zj.utils.map.MapUtils;

import org.jetbrains.annotations.NotNull;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.Marker;
import org.osmdroid.views.overlay.Polyline;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.zj.osm.App.getInstances;
import static com.zj.osm.utils.MyUtils.Distance;
import static com.zj.osm.utils.MyUtils.rotation;
public class LineUtils {
    private static final LineUtils ourInstance = new LineUtils();
    private Context mcontext;
    public static LineUtils getInstance() {
        return ourInstance;
    }
    //知道线条线端计算角度
    public static double getLineLenthAndAngle(com.zj.osm.entity.greendao.Point point,com.zj.osm.entity.greendao.Point points, double b_lenght) {
            List<Line> sizeGuanlianxian = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.ProjectId.eq(point.getProjectId()), LineDao.Properties.End_id.eq(point.getUid())).build().list();
            if (sizeGuanlianxian != null && sizeGuanlianxian.size() > 0) {
                com.zj.osm.entity.greendao.Point guanPoint = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(point.getProjectId()), PointDao.Properties.Uid.eq(sizeGuanlianxian.get(0).getStart_id())).build().unique();
                if (guanPoint != null) {
                    double lenght = MapUtils.distance(guanPoint.getLatitude(), guanPoint.getLongitude(), points.getLatitude(), points.getLongitude());
                    double a_length = Double.parseDouble(sizeGuanlianxian.get(0).getLength());
                    double b_length = b_lenght;
                    double c_length = lenght;
                    if (b_lenght > 0.00000000001 && c_length > 0.000000000001) {
                        ///求c的角度
                        double ttB = (Math.pow(a_length, 2) + Math.pow(b_length, 2) - Math.pow(c_length, 2)) / (2 * a_length * b_length);
                        DecimalFormat df = new DecimalFormat("0.000000000");
                        double angles = 180 / Math.PI * Math.acos(Double.parseDouble(df.format(ttB)));
                        DecimalFormat dff = new DecimalFormat("0.00");
                        double angless=Double.parseDouble(dff.format(180.0-angles));
                        return angless;
                    }
                }
            }
        return 0.0;
    }
    private LineUtils() {
    }
    ///查询线的remark
    public String getLineRemarker( String reMarkerName) {
        String ReMark = "";
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType  where name='" + reMarkerName + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ReMark = cursor.getString(6);
            break;
        }
        cursor.close();
        return ReMark;
    }
    ///查询线的高压抵押线路的类型
    public String getEquipType(String reMarkerName) {
        String equipTypeName = "";
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType m where m.id =" + "'" + reMarkerName + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            equipTypeName = cursor.getString(1);
        }

        cursor.close();
        return equipTypeName;
    }
    /**
     * itemId项目id
     * marName上一个点点Mark
     */
   public String getInLinesMaxNumber(Long itemId) {
        int numberString = 1;
        List<Line> itemLines = getItemLines(itemId);
        assert itemLines != null;
        for (int index = 0; index<itemLines.size(); index++) {
            if (HasDigit(itemLines.get(index).getName())) {//如果包含数字那么进行筛选最大值
                int number = getNumberInString(itemLines.get(index).getName(), itemLines.size());
                if (numberString < number) {
                    numberString = number;
                }
            }

        }
        //替换拿到Mark里面的文字部分。

        return numberString+"";
    }

    private List<Line> getItemLines(Long itemId) {
        List<Line> allItemLine = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(itemId)).build().list();
        return allItemLine;
    }

    /***
     * 判断一个字符串是否含有数字
     * content:字符串内容
     */
    boolean HasDigit(String content ){
        boolean flag = false;
        Pattern p = Pattern.compile(".*\\d+.*");
        Matcher m = p.matcher(content);
        if (m.matches()) {
            flag = true;
        }
        return flag;
    }
    private int getNumberInString(String mark, int lineNumber) {
        int number = lineNumber;
        String regEx = "[0-9]+(?=[^0-9]*$)";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(mark);
        while (m.find()) {
            number = Integer.parseInt(m.group(0)) + 1;
        }
        return number;
    }
    public Line getGline_xianlu(Line line, Project items) {
        List<Line> lines = getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.End_id.eq(line.getStart_id()), LineDao.Properties.Start_id.eq(line.getStart_id())).where(LineDao.Properties.Type.like("%" + line.getType() + "%"), LineDao.Properties.ModuleID.notEq("")).build().list();
        if (lines.size() > 0) {//表示有线
            return lines.get(0);
        }

        if (items.getGanxinModuleId() != null||items.getDilanModuleId()!=null) {
            Line DefaultLine = new Line();
            //设置杆塔
            /*if(items.getGanxinModuleId()!=null) {
                DefaultLine.setModuleID(items.getJiakongModuleId());
                DefaultLine.setType(getEquipType(items.getJiakongEquipId()));
                DefaultLine.setMethodName(getEquipType(items.getGanxinModuleId()));
            }else{
                DefaultLine.setType(line.getType());
            }*/
            //设置线路
            if (line.getType().contains("架空")) {
                if(items.getGanxinModuleId()!=null) {
                    DefaultLine.setModuleID(items.getJiakongModuleId());
                    DefaultLine.setModuleTxt(PointsUtils.Companion.getModuleLocal(items.getJiakongModuleId()) == null ? "" : PointsUtils.Companion.getModuleLocal(items.getJiakongModuleId()).getModuleName());
                    DefaultLine.setTypes(PointsUtils.Companion.getModuleLocal(items.getJiakongModuleId()) == null ? "" : PointsUtils.Companion.getModuleLocal(items.getJiakongModuleId()).getModuleName());
                    DefaultLine.setTypeId(items.getJiakongModuleId());
                    if(items.getJiakongEquipId()!=null){
                        DefaultLine.setType(getEquipType(items.getJiakongEquipId()));
                    }else{
                        DefaultLine.setType(line.getType());
                    }
                    DefaultLine.setMethodName(getEquipType(items.getGanxinModuleId()));
                }

            } else {//电缆
                if(items.getDilanModuleId()!=null) {
                    DefaultLine.setModuleID(items.getDilanModuleId());
                    DefaultLine.setModuleTxt(PointsUtils.Companion.getModuleLocal(items.getDilanModuleId()) == null ? "" : PointsUtils.Companion.getModuleLocal(items.getDilanModuleId()).getModuleName());
                    DefaultLine.setTypes(PointsUtils.Companion.getModuleLocal(items.getDilanModuleId()) == null ? "" : PointsUtils.Companion.getModuleLocal(items.getDilanModuleId()).getModuleName());
                    DefaultLine.setTypeId(items.getDilanModuleId());
                    if(items.getDilanEquipId()!=null){
                        DefaultLine.setType(getEquipType(items.getDilanEquipId()));
                    }else{
                        DefaultLine.setType(line.getType());
                    }
                    DefaultLine.setMethodName(getEquipType(items.getGanxinModuleId()));
                }
            }
            DefaultLine.setPath(items.getPath()!=null?items.getPath():"");
            return DefaultLine;
        }
        return null;
    }

    //查询线的选型
    public String getDefaultLineType(String lineName) {
        String defualtLineType = "1";
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle")
        Cursor cursor = db.rawQuery("select * from EquipType m where m.name =" + "'" + lineName + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            defualtLineType = cursor.getString(4);
        }

        cursor.close();
        db.close();
        return defualtLineType;
    }
    /**
     * 保存bitmap为png图片
     *
     * @param bitmap 图片
     */
    public void saveBitmap(Bitmap bitmap, Project items) {

        File files = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + items.getName());
        if (!files.exists() && !files.isDirectory()) {
            files.mkdirs();
        }
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + items.getName() + "/" + items.getName() + items.getId() + ".png");
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public List<Point> getTongGanBingjia(Point s_point, Point e_point, int dis, String methodName) {
        double k = (e_point.y - s_point.y) * 1.0 / (e_point.x - s_point.x) * 1.0;
        double a = Math.atan(k);
        double b = (180 * a) / 3.1415926;

        Point gpoint1;
        Point gpoint2;

        List<Point> list = new ArrayList<>();

        if (-45.0 < b && b < 45.0) {
            if (methodName.equals("1")) {
                gpoint1 = new Point(s_point.x, s_point.y - dis);
                gpoint2 = new Point(e_point.x, e_point.y - dis);
            } else {
                gpoint1 = new Point(s_point.x, s_point.y + dis);
                gpoint2 = new Point(e_point.x, e_point.y + dis);
            }
            list.add(gpoint1);
            list.add(gpoint2);
        } else {
            if (methodName.equals("1")) {
                gpoint1 = new Point(s_point.x - dis, s_point.y);
                gpoint2 = new Point(e_point.x - dis, e_point.y);
            } else {
                gpoint1 = new Point(s_point.x + dis, s_point.y);
                gpoint2 = new Point(e_point.x + dis, e_point.y);
            }
            list.add(gpoint1);
            list.add(gpoint2);
        }
        return list;
    }

    /**
     * 进行新建需要绘制到mapActivity上面到线路样式
     * @param line
     * @return
     */
    public Polyline getPolyLine(Line line) {
        Polyline ooPolyline = null;
        int lineColor = Color.BLACK;
        //用户如未设置电压等级，则默认电压等级为10kV，
        //10kV线路颜色为红色，
        //380V及220V线路颜色为蓝色，
        //同时存在高压及低压线路时，颜色为红色。
        switch (getModuleVectorByModuleID(line.getModuleID())) {
            case "380V":
            case "220V":
                lineColor = Color.parseColor("#1296db");
                break;
            default:
                lineColor = Color.parseColor("#DA382F");
                break;
        }
        /*switch (line.getState()) {
            case "新建":
                lineColor = Color.parseColor("#DA382F");
                break;
            case "原有":
                lineColor = Color.BLACK;
                break;
            case "改造":
                lineColor = Color.argb(255, 189, 121, 64);
                break;
            case "拆除":
                lineColor = Color.GRAY;
                break;
        }*/
        // Line{id=205, lineId='null', cid='b70e7c90-5150-48d7-8287-898c0ef6c81d', start_id='2451a54d-691b-4a49-b0ac-09c8a5ec880f', end_id='8f9a6c62-9c81-4fb9-a29b-8bcb6af68ba7', projectId=5, name='线路1#', category='null', type='架空线路', typeId='11', types='null', pipe_laying_state='null', state='新建', backNum='1', num='null', methodName='null', length='148', line_len='null', item_id=5, latA='39.05493025001159', latB='39.05623826686009', lonA='117.29280710220337', lonB='117.29253888130188', name_a=0, name_b=0, parallelPole='0', isT='null', path='null', moduleID='', moduleTxt='', legendTypeKey='TY_DHJKX', equipmentList=null, pointList=null, daoSession=com.zj.osm.entity.db.DaoSession@e2398ca, myDao=com.zj.osm.entity.db.LineDao@e334558}
        //[Line{id=202, lineId='null', cid='e15bea67-7429-4558-8552-208754dd1df1', start_id='4235745c-b4f1-471d-a324-f6c0bf778ade', end_id='01f141b8-9fb8-477a-bdf8-820232a9967d', projectId=5, name='线路1#', category='null', type='架空线路', typeId='11', types='null', pipe_laying_state='null', state='新建', backNum='1', num='1', methodName='null', length='143.07', line_len='null', item_id=5, latA='39.05404295090495', latB='39.054322055030156', lonA='117.28845119476318', lonB='117.29006856679916', name_a=0, name_b=0, parallelPole='null', isT='null', path='null', moduleID='', moduleTxt='', legendTypeKey='TY_DHJKX', equipmentList=null, pointList=null, daoSession=com.zj.osm.entity.db.DaoSession@e334558, myDao=com.zj.osm.entity.db.LineDao@c7f7050},
        // Line{id=203, lineId='null', cid='cb401f84-b81a-416d-9a32-a4d2428ae6a3', start_id='01f141b8-9fb8-477a-bdf8-820232a9967d', end_id='f1d3a5a8-d855-4ffc-935d-276beaf6c66c', projectId=5, name='线路1#', category='null', type='架空线路', typeId='11', types='null', pipe_laying_state='null', state='新建', backNum='1', num='1', methodName='null', length='143.07', line_len='null', item_id=5, latA='39.054322055030156', latB='39.05460115915537', lonA='117.29006856679916', lonB='117.29168593883514', name_a=0, name_b=0, parallelPole='null', isT='null', path='null', moduleID='', moduleTxt='', legendTypeKey='TY_DHJKX', equipmentList=null, pointList=null, daoSession=com.zj.osm.entity.db.DaoSession@e334558, myDao=com.zj.osm.entity.db.LineDao@c7f7050}]
        //Log.e("ooPolyline======", ooPolyline.toString());
        if (line.getType() != null && !line.getType().contains("电缆")) {//浅色
            if (line.getTypes() == null || line.getTypes().isEmpty()) {
                ooPolyline = createPolylineOptions(6, lineColor, line, false);//2

            } else {
                ooPolyline = createPolylineOptions(11, lineColor, line, false);//4
            }
        } else {//深色
            if (line.getTypes() == null || line.getTypes().isEmpty()) {
                Log.e("linType===", line.toString());
                ooPolyline = createPolylineOptions(6, lineColor, line, true);//2
            } else {
                Log.e("linType===", line.getTypes());
                ooPolyline = createPolylineOptions(11, lineColor, line, true);
            }
        }
        Log.e("ooPolyline======", ooPolyline.toString());
        return ooPolyline;
    }
    /**
     * 不同类型线的样式不同
     *
     * @param width  粗细
     * @param black  颜色
     * @param line   路径
     * @param
     * @param b
     * @param
     * @return 线
     */
    private Polyline createPolylineOptions(int width, int black, Line line, boolean b) {
        Polyline polyline = new Polyline();
        polyline.setWidth(width);
        polyline.setColor(black);
        if(b){
            polyline.getPaint().setPathEffect(new DashPathEffect(new float[]{32, 32}, 22));//phase
            polyline.setGeodesic(b);//虚线？
        }else{
            polyline.setGeodesic(b);
        }
        polyline.setPoints(getLineGeoPoint(line));//设置线到开始点和结束点
        polyline.setRelatedObject(line);
        polyline.setId(String.valueOf(line.getId()));
        return polyline;
    }
    /**
     * 通过线获取到线的坐标（经纬度）
     *
     * @param line 线
     * @return 线的两端的经纬度坐标
     */
    public List<GeoPoint> getLineGeoPoint(Line line) {
        List<GeoPoint> geoPointList = new ArrayList<>();
        //List<Point> pointList = line.getPointList();
        geoPointList.add(new GeoPoint(Double.parseDouble(line.getLatA()), Double.parseDouble(line.getLonA())));
        geoPointList.add(new GeoPoint(Double.parseDouble(line.getLatB()), Double.parseDouble(line.getLonB())));
        return geoPointList;
    }

    /**
     * 绘制线路上面的类型Mark
     * @param line
     * @param mMapView
     * @param mGeoPoint
     * @param btn_Length_isCheck
     * @param lng1
     * @param lng2
     * @return
     */
    public Marker getLineTypeMarker(Line line, MapView mMapView, GeoPoint mGeoPoint,boolean btn_Length_isCheck,LatLng lng1,LatLng lng2) {
        Marker lineTypeMarker = new Marker(mMapView);
        lineTypeMarker.setPanToView(false);
        lineTypeMarker.setOnMarkerClickListener((marker, mapView) -> false);
        lineTypeMarker.setPosition(mGeoPoint);//设置显示位置
        lineTypeMarker.setTextLabelBackgroundColor(Color.parseColor("#ffffff"));
        lineTypeMarker.setTextLabelFontSize(29);
        //lineTypeMarker.
        if(line.getTypes()==null||line.getTypes().equals("null")||line.getTypes().isEmpty()){
            lineTypeMarker.setTextIcon(" ");

        }else{
            String vector=getModuleVector(line.getModuleID());
            String number_line=getNumberLine(line);
            lineTypeMarker.setTextIcon(line.getTypes()+vector+number_line);
        }
        lineTypeMarker.setAnchor(0.3f, 0f);
        lineTypeMarker.setVisible(btn_Length_isCheck);
        lineTypeMarker.setId(String.valueOf(line.getId()));
        lineTypeMarker.setRotation(rotation(lng1, lng2));
        lineTypeMarker.setRelatedObject(line);
        return lineTypeMarker;
    }

    private String getNumberLine(Line line) {
        List lineNumber=App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(line.getStart_id()),LineDao.Properties.End_id.eq(line.getEnd_id())).list();
        return lineNumber.size()==0?",1":","+lineNumber.size();
    }

    private String getModuleVector(String moduleId) {
        String vector="";
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        @SuppressLint("Recycle")
        //ModuleID	ModuleName	ModuleTypeKey	ModuleCode	Voltage	Book	Remark	State	StateFlag	operatetime
        Cursor cursor = db.rawQuery("select Voltage from Module  where ModuleID='"+moduleId+"'"+" and State=1", null); //此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            vector=cursor.getString(0);
            if(vector.contains("380")||vector.contains("220")) {
               vector=","+vector.replace("V", "");
            }else{
                vector="";
            }
        }
        cursor.close();
        return vector;
    }
    private String getModuleVectorByModuleID(String moduleId) {
        String vector="";
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        @SuppressLint("Recycle")
        //ModuleID	ModuleName	ModuleTypeKey	ModuleCode	Voltage	Book	Remark	State	StateFlag	operatetime
        Cursor cursor = db.rawQuery("select Voltage from Module  where ModuleID='"+moduleId+"'"+" and State=1", null); //此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            vector=cursor.getString(0);
        }
        cursor.close();
        return vector;
    }

    /**
     * 绘制线路上面的档距Mark
     * @param line
     * @param mMapView
     * @param mGeoPoint
     * @param btn_Length_isCheck
     * @param lng1
     * @param lng2
     * @return
     */
    public Marker getLineDistanceMarker(@NotNull Line line, MapView mMapView, GeoPoint mGeoPoint, boolean btn_Length_isCheck, LatLng lng1, LatLng lng2) {
        String legthString = line.getLength();
        BigDecimal bg = new BigDecimal(Double.parseDouble(legthString)).setScale(1, RoundingMode.UP);
        legthString = bg.intValue() + "";
        Marker lineDangjuMarker = new Marker(mMapView);
        lineDangjuMarker.setPanToView(false);
        lineDangjuMarker.setOnMarkerClickListener((marker, mapView) -> false);
        lineDangjuMarker.setPosition(mGeoPoint);//设置显示位置
        //lineDangjuMarker.setTextLabelForegroundColor(Color.alpha(0));
        lineDangjuMarker.setTextLabelBackgroundColor(Color.alpha(0));
        lineDangjuMarker.setTextLabelFontSize(35);
        lineDangjuMarker.setTextIcon(legthString + "m");
        lineDangjuMarker.setAnchor(0.9f, 1.2f);
        lineDangjuMarker.setVisible(btn_Length_isCheck);
        lineDangjuMarker.setId(String.valueOf(line.getId()));
        lineDangjuMarker.setRotation(rotation(lng1, lng2));
        lineDangjuMarker.setRelatedObject(line);
        return lineDangjuMarker;
    }
    /**
     * 获取同杆并架的线
     *
     * @param pointsFist
     * @param endPoints
     * @param addNum
     * @param degrees
     * @param methodName
     * @param project
     *
     * */
    public Line getTongGanNewLine(com.zj.osm.entity.greendao.Point pointsFist, com.zj.osm.entity.greendao.Point endPoints, Double addNum, double degrees, int methodName,Project project) {
        BigDecimal bg = new BigDecimal(Distance(Double.valueOf(pointsFist.getLatitude() + ""), Double.valueOf(pointsFist.getLongitude() + ""), Double.valueOf(endPoints.getLatitude()), Double.valueOf(endPoints.getLongitude()))).setScale(0, RoundingMode.UP);
        int lengths = bg.intValue();
        Line line = new Line();
        line.setCid(getUUID());
        List<Line> lineList = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(project.getId())).build().list();
        line.setId(null);
        line.setItem_id(project.getId());
        line.setProjectId(project.getId());
        line.setParallelPole("同杆并架");
        line.setMethodName(methodName + "");
        if (degrees < 5 && degrees > -5) {
            line.setLatB(endPoints.getLatitude() + "");
            line.setLonB(endPoints.getLongitude() + addNum + "");
            line.setLatA(pointsFist.getLatitude() + "");
            line.setLonA(pointsFist.getLongitude() + addNum + "");
        } else {
            line.setLatB(endPoints.getLatitude() + addNum + "");
            line.setLonB(endPoints.getLongitude() + "");
            line.setLatA(pointsFist.getLatitude() + addNum + "");
            line.setLonA(pointsFist.getLongitude() + "");
        }
        line.setStart_id(pointsFist.getUid());
        line.setEnd_id(endPoints.getUid());
        line.setLength(lengths + "");
        line.setBackNum("1");
        line.setLegendTypeKey(getLineRemarker("低压架空线路"));
        //TODO 这里修改了    line.setType("架空线路");
        line.setType("架空线路");
        line.setTypeId("11");
        if (lineList.size() > 0) {
            //2019年11月18日 int mad = (int) (lineList.get(lineList.size() - 1).getId() + 1);
            line.setName((lineList.size() + 1) + "#");
        } else {
            line.setName(1 + "#");
        }
        line.setState("新建");
        line.setNum("1");
        //TODO 保存线
        return line;
    }
    public SendPointResult getTongGanBingjiaResult(int lineNum,List<com.zj.osm.entity.greendao.Point> resultPoints,MapView mMapView,Project project,double degrees) {
        if (lineNum == 0) {
            //知道了 第一个点和最后一个点   pointFist   latLngList
            //知道了 第一个点和最后一个点   pointFist   latLngList
            for (int i = 0; i < resultPoints.size() - 1; i++) {
                com.zj.osm.entity.greendao.Point onePoints = resultPoints.get(i);
                com.zj.osm.entity.greendao.Point twoPoints = resultPoints.get(i + 1);
                List<Line> lineListaa = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(project.getId()), LineDao.Properties.Start_id.eq(onePoints.getUid()), LineDao.Properties.End_id.eq(twoPoints.getUid())).build().list();
                List<Line> lineListbb = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(project.getId()), LineDao.Properties.Start_id.eq(twoPoints.getUid()), LineDao.Properties.End_id.eq(onePoints.getUid())).build().list();
                lineListaa.addAll(lineListbb);
                int lineNumab = lineListaa.size();
                if (lineNumab < 2) {
                    return new SendPointResult(onePoints, twoPoints, 0);
                }
            }

        } else if (lineNum == 1) {
            for (int i = 0; i < resultPoints.size() - 1; i++) {
                com.zj.osm.entity.greendao.Point onePoints = resultPoints.get(i);
                com.zj.osm.entity.greendao.Point twoPoints = resultPoints.get(i + 1);
                List<Line> lineListaa = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.ProjectId.eq(project.getId()), LineDao.Properties.Start_id.eq(onePoints.getUid()), LineDao.Properties.End_id.eq(twoPoints.getUid())).build().list();
                List<Line> lineListbb = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.ProjectId.eq(project.getId()), LineDao.Properties.Start_id.eq(twoPoints.getUid()), LineDao.Properties.End_id.eq(onePoints.getUid())).build().list();
                lineListaa.addAll(lineListbb);
                int lineNumab = lineListaa.size();
                if (lineNumab < 2) {
                    return new SendPointResult(onePoints, twoPoints, 1);
                    // addTongGanNewLine(onePoints, twoPoints, 0.000025, degrees, 10);
                }
            }
        } else {
            for (int i = 0; i < resultPoints.size() - 1; i++) {
                com.zj.osm.entity.greendao.Point onePoints = resultPoints.get(i);
                com.zj.osm.entity.greendao.Point twoPoints = resultPoints.get(i + 1);
                Point onePoint = mMapView.getProjection().toPixels(new GeoPoint(onePoints.getLatitude(), onePoints.getLongitude()), null);
                Point twoPoint = mMapView.getProjection().toPixels(new GeoPoint(twoPoints.getLatitude(), twoPoints.getLongitude()), null);
                List<Point> onePointss = getTongGanBingjia(onePoint, twoPoint, (int) degrees, "0");
                LatLng onetLat = new LatLng(mMapView.getProjection().fromPixels(onePointss.get(0).x, onePointss.get(0).y).getLatitude(), mMapView.getProjection().fromPixels(onePointss.get(0).x, onePointss.get(0).y).getLongitude());
                LatLng twoLat = new LatLng(mMapView.getProjection().fromPixels(onePointss.get(1).x, onePointss.get(1).y).getLatitude(), mMapView.getProjection().fromPixels(onePointss.get(1).x, onePointss.get(1).y).getLongitude());
                onePoints.setLatitude(onetLat.latitude);
                onePoints.setLongitude(onetLat.longitude);
                twoPoints.setLatitude(twoLat.latitude);
                twoPoints.setLongitude(twoLat.longitude);
                List<Line> lineListaa = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.ProjectId.eq(project.getId()), LineDao.Properties.Start_id.eq(onePoints.getUid()), LineDao.Properties.End_id.eq(twoPoints.getUid())).build().list();
                List<Line> lineListbb = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.ProjectId.eq(project.getId()), LineDao.Properties.Start_id.eq(twoPoints.getUid()), LineDao.Properties.End_id.eq(onePoints.getUid())).build().list();
                lineListaa.addAll(lineListbb);
                int lineNumab = lineListaa.size();
                if (lineNumab < 2) {
                    return new SendPointResult(onePoints, twoPoints, 2);
                    //drawParallelWithBar();
                }

            }
        }
        return null;
    }

    /**
     * 获取关联线
     * @param
     */
    public List<Line> getGuanLianLine(com.zj.osm.entity.greendao.Point ptA) {
        List<Line> gulianLine = new ArrayList<>();
        //1。如果端头一定可以看见。
        //这里判断如果线不是T线且连点有2条那么就隐藏其他的可以进行显示。
        List<com.zj.osm.entity.greendao.Point> allguanLianPoints = new ArrayList<>();
        if (ptA != null) {
            List<Line> allguanLian = getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Start_id.eq(ptA.getUid()), LineDao.Properties.End_id.eq(ptA.getUid())).list();
            for (int i = 0; i < allguanLian.size(); i++) {
                List<com.zj.osm.entity.greendao.Point> pointLists = getInstances().getDaoSession().getPointDao().queryBuilder().whereOr(PointDao.Properties.Uid.eq(allguanLian.get(i).getStart_id()), PointDao.Properties.Uid.eq(allguanLian.get(i).getEnd_id())).list();
                allguanLianPoints.addAll(pointLists);
            }
            allguanLianPoints = new ArrayList(new HashSet(allguanLianPoints));
            if (allguanLianPoints.size() == 2) {//如果是有切只有一个关联点那么一定全部继承。
                gulianLine = getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.End_id.eq(ptA.getUid()), LineDao.Properties.Start_id.eq(ptA.getUid())).build().list();

            } else if (allguanLianPoints.size() > 2) {
                List<Line> allGuanlianLine = getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Start_id.eq(ptA.getUid()), LineDao.Properties.End_id.eq(ptA.getUid())).whereOr(LineDao.Properties.ParallelPole.isNull(), LineDao.Properties.ParallelPole.eq("0"), LineDao.Properties.ParallelPole.eq("同杆并架")).list();
                List<Line> unitqGuanlianLine = new ArrayList<>();
                List<String> unitqGuanlianLineName = new ArrayList<>();
                for (int i = 0; i < allGuanlianLine.size(); i++) {
                    if (unitqGuanlianLineName.contains(allGuanlianLine.get(i).getName())) {
                        unitqGuanlianLineName.remove(allGuanlianLine.get(i).getName());
                        for (int j = 0; j < unitqGuanlianLine.size(); j++) {
                            if (unitqGuanlianLine.get(j).getName().equals(allGuanlianLine.get(i).getName())) {
                                unitqGuanlianLine.remove(unitqGuanlianLine.get(j));
                            }
                        }
                    } else {
                        unitqGuanlianLineName.add(allGuanlianLine.get(i).getName());
                        unitqGuanlianLine.add(allGuanlianLine.get(i));
                    }
                }
                unitqGuanlianLineName.clear();
                gulianLine.clear();
                gulianLine.addAll(unitqGuanlianLine);
            }

        }
        return  gulianLine;
    }
    /**
     * 获取UUID
     *
     * @return uuid
     */
    private String getUUID() {
        return UUID.randomUUID() + "";
    }

    public Line getConneLine(Line l, Project project, com.zj.osm.entity.greendao.Point ptA, com.zj.osm.entity.greendao.Point ptB) {
            Line line = new Line();
            line.setCid(getUUID());
            line.setItem_id(project.getId());
            line.setProjectId(project.getId());
            line.setStart_id(ptA.getUid());
            line.setLatA(ptA.getLatitude().toString());
            line.setLonA(ptA.getLongitude().toString());
            line.setMethodName("0");
            line.setEnd_id(ptB.getUid());
            line.setLatB(ptB.getLatitude().toString());
            line.setLonB(ptB.getLongitude().toString());
            BigDecimal bg = new BigDecimal(Distance(Double.valueOf(ptA.getLatitude() + ""), Double.valueOf(ptA.getLongitude() + ""), Double.valueOf(ptB.getLatitude() + ""), Double.valueOf(ptB.getLongitude() + ""))).setScale(0, RoundingMode.UP);
            int lengths = bg.intValue();
            line.setLength(lengths + "");
            line.setBackNum("1");
            line.setNum("1");

            //TODO 这里修改了
            List<Line> lineList = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(project.getId())).build().list();
            int mad = 1;
            if (lineList.size() > 0) {
                mad = (int) (lineList.get(lineList.size() - 1).getId() + 1);
            }
            if ((ptA.getName().equals("杆塔") || ptA.getSblx().equals("柱上变压器")) && (ptB.getName().equals("杆塔") || ptB.getSblx().equals("柱上变压器"))) {
                line.setType("架空线路");
                line.setLegendTypeKey(getLineRemarker("高压架空线路"));
                line.setTypeId("11");
                //String line_names = "线路" + getInLinesMaxNumber(cid) + "#";
                line.setName(l.getName());
                line.setPipe_laying_state("新建");
            } else {//实现
                line.setType("电缆");
                line.setTypeId("12");
                //String line_names = "线路" + getInLinesMaxNumber(cid) + "#";
                line.setName(l.getName());
                line.setLegendTypeKey(getLineRemarker("高压电缆线路"));
                line.setPipe_laying_state("新建");

            }

            line.setState("新建");
            line.setNum("1");
            if (l.getModuleID() != null && !l.getModuleID().isEmpty()) {
                if (l.getType().contains(line.getType())) {//类型相同的。
                    line.setNum(l.getNum());
                    line.setModuleID(l.getModuleID());
                    line.setModuleTxt(l.getModuleTxt());
                    line.setTypes(l.getTypes());
                    line.setTypeId(l.getTypeId());
                    line.setType(l.getType());
                    line.setMethodName(l.getMethodName());
                    line.setPath(l.getPath());
                    if (l.getParallelPole() != null && l.getParallelPole().equals("同杆并架")) {
                        line.setParallelPole(l.getParallelPole());
                        if (l.getLegendTypeKey() != null && !l.getLegendTypeKey().equals("null") && !l.getLegendTypeKey().isEmpty()) {
                            line.setLegendTypeKey(l.getLegendTypeKey());
                        }
                    } else {
                        line.setParallelPole("0");
                        //如果选型关联的线1的legendTypeKey有关联的线的选型。高低压之类的我们也需要继承。
                        if (l.getLegendTypeKey() != null && !l.getLegendTypeKey().equals("null") && !l.getLegendTypeKey().isEmpty()) {
                            line.setLegendTypeKey(l.getLegendTypeKey());
                            //回 滚
                        }
                    }
                    line.setState(l.getState());
                } else {//类型不同的线寻找关联的。
                    Line defaultLine =getGline_xianlu(line, project);
                    line.setNum(l.getNum());
                    line.setModuleID(defaultLine.getModuleID());
                    line.setModuleTxt(defaultLine.getModuleTxt());
                    line.setTypes(defaultLine.getTypes());
                    line.setTypeId(defaultLine.getTypeId());
                    line.setType(defaultLine.getType());
                    line.setMethodName(defaultLine.getMethodName());
                    line.setPipe_laying_state("新建");
                    line.setPath(defaultLine.getPath());
                    if (l.getParallelPole() != null && l.getParallelPole().equals("同杆并架")) {
                        line.setParallelPole(l.getParallelPole());
                        if (l.getLegendTypeKey() != null && !l.getLegendTypeKey().equals("null") && !l.getLegendTypeKey().isEmpty()) {
                            line.setLegendTypeKey(l.getLegendTypeKey());
                        }
                    } else {
                        line.setParallelPole("0");
                        //如果选型关联的线1的legendTypeKey有关联的线的选型。高低压之类的我们也需要继承。
                    }
                    line.setState(l.getState());
                }

            } else {
                if (getInstances().isXinJian) {
                    line.setState("新建");

                } else {
                    line.setState("原有");
                }
                Line defaultLine =getGline_xianlu(line,project);
                if (defaultLine != null && defaultLine.getModuleID() != null && !defaultLine.getModuleID().isEmpty()) {
                    line.setNum("1");
                    line.setModuleID(defaultLine.getModuleID());
                    line.setModuleTxt(defaultLine.getModuleTxt());
                    line.setTypes(defaultLine.getTypes());
                    line.setTypeId(defaultLine.getTypeId());
                    line.setType(defaultLine.getType());
                    line.setMethodName(defaultLine.getMethodName());
                    line.setPipe_laying_state("新建");
                    line.setPath(defaultLine.getPath());
                }
            }
            getInstances().getDaoSession().getLineDao().insert(line);
            return line;
    }

    public Line getConneLineNew(Project project, com.zj.osm.entity.greendao.Point ptA, com.zj.osm.entity.greendao.Point ptB) {
        Line line = new Line();
        line.setCid(getUUID());
        line.setItem_id(project.getId());
        line.setProjectId(project.getId());

        line.setStart_id(ptA.getUid());
        line.setLatA(ptA.getLatitude().toString());
        line.setLonA(ptA.getLongitude().toString());

        line.setEnd_id(ptB.getUid());
        line.setLatB(ptB.getLatitude().toString());
        line.setLonB(ptB.getLongitude().toString());
        BigDecimal bg = new BigDecimal(Distance(Double.valueOf(ptA.getLatitude() + ""), Double.valueOf(ptA.getLongitude() + ""), Double.valueOf(ptB.getLatitude() + ""), Double.valueOf(ptB.getLongitude() + ""))).setScale(0, RoundingMode.UP);
        int lengths = bg.intValue();
        line.setLength(lengths + "");
        line.setBackNum("1");
        line.setNum("1");
        line.setMethodName("0");
        line.setParallelPole("0");
        //TODO 这里修改了
        List<Line> lineList = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(project.getId())).build().list();
        int mad = 1;
        if (lineList.size() > 0) {
            mad = (int) (lineList.get(lineList.size() - 1).getId() + 1);
        }
        if ((ptA.getName().equals("杆塔") || ptA.getSblx().equals("柱上变压器")) && (ptB.getName().equals("杆塔") || ptB.getSblx().equals("柱上变压器"))) {
            line.setType("架空线路");
            line.setLegendTypeKey(getLineRemarker("高压架空线路"));
            line.setTypeId("11");
            String line_names = "线路" + getInLinesMaxNumber(project.getId()) + "#";
            line.setName(line_names);
            line.setPipe_laying_state("新建");
        } else {//实现
            line.setType("电缆线路");
            line.setTypeId("12");
            String line_names = "线路" + getInLinesMaxNumber(project.getId()) + "#";
            line.setName(line_names);
            line.setLegendTypeKey(getLineRemarker("高压电缆线路"));
            line.setPipe_laying_state("新建");

        }
        line.setState("新建");
        line.setNum("1");
        long id= getInstances().getDaoSession().getLineDao().insert(line);
        Log.e("line======",line.toString());
        return line;
    }


    /**
     * 求pOut在pLine以及pLine2所连直线上的投影点
     *
     * @param pLine
     * @param pLine2
     * @param pOut
     * @param
     */
    public static com.zj.osm.entity.greendao.Point getProjectivePoint(com.zj.osm.entity.greendao.Point pLine, com.zj.osm.entity.greendao.Point pLine2, com.zj.osm.entity.greendao.Point pOut) {
        double k = 0;
        try {
            k = getSlope(pLine.getLongitude(), pLine.getLatitude(), pLine2.getLongitude(), pLine2.getLatitude());
        } catch (Exception e) {
            k = 0;
        }

        double x1 = new BigDecimal(Distance(pLine.getLatitude(), pLine.getLongitude(), pOut.getLatitude(), pOut.getLongitude())).setScale(0, RoundingMode.UP).doubleValue();

        double x2 = new BigDecimal(Distance(pLine2.getLatitude(), pLine2.getLongitude(), pOut.getLatitude(), pOut.getLongitude())).setScale(0, RoundingMode.UP).doubleValue();

        double x3 = new BigDecimal(Distance(pLine2.getLatitude(), pLine2.getLongitude(), pLine.getLatitude(), pLine.getLongitude())).setScale(0, RoundingMode.UP).doubleValue();

        double y = (x1 * x3) / (x1 + x2);

        double degree = getAngle(pLine.getLongitude(), pLine.getLatitude(), pLine2.getLongitude(), pLine2.getLatitude());
        AngleUtil angleUtil = new AngleUtil(Double.valueOf(pLine.getLongitude()), pLine.getLatitude());
        LatLng myLatLng = AngleUtil.getMyLatLng(angleUtil, y, degree);

        com.zj.osm.entity.greendao.Point pProject = new com.zj.osm.entity.greendao.Point();

        if (k == 0) {//垂线斜率不存在情况
            pProject.setLongitude(pOut.getLongitude());
            pProject.setLatitude(pLine.getLatitude());
        } else {
            pProject.setLongitude(myLatLng.longitude);
            pProject.setLatitude(myLatLng.latitude);
        }


        return pProject;
    }
    /**
     * 已知两点经纬度求方位角
     */
    public static double getAngle(double lon1, double lat1, double lon2, double lat2) {
        double fLat = Math.PI * (lat1) / 180.0;
        double fLng = Math.PI * (lon1) / 180.0;
        double tLat = Math.PI * (lat2) / 180.0;
        double tLng = Math.PI * (lon2) / 180.0;

        double degree = (Math.atan2(Math.sin(tLng - fLng) * Math.cos(tLat), Math.cos(fLat) * Math.sin(tLat) - Math.sin(fLat) * Math.cos(tLat) * Math.cos(tLng - fLng))) * 180.0 / Math.PI;
        if (degree >= 0) {
            return degree;
        } else {
            return 360 + degree;
        }
    }
    /**
     * 通过两个点坐标计算斜率
     * 已知A(x1,y1),B(x2,y2)
     * 1、若x1=x2,则斜率不存在；
     * 2、若x1≠x2,则斜率k=[y2－y1]/[x2－x1]
     *
     * @param x1
     * @param y1
     * @param x2
     * @param y2
     * @throws Exception 如果x1==x2,则抛出该异常
     */
    public static double getSlope(double x1, double y1, double x2, double y2) throws Exception {
        if (x1 == x2) {
            throw new Exception("Slope is not existence,and div by zero!");
        }
        return (y2 - y1) / (x2 - x1);
    }
}
